%h3
  = @html_title
  = link_to "新建#{@plate_word}", new_post_path(plate_id: params[:plate_id]), class: 'btn btn-xs btn-primary'

%table.table.table-condensed.table-bordered
  %tr
    %th{width: '5%'} 序号
    %th{width: '20%'} 标题
    %th{width: '20%'} 封面
    %th{width: '20%'} 状态
    %th{width: '20%'} 操作
    %th{width: '15%'} 排序
  - @posts.each do |post|
    %tr
      %td= post.order_num
      %td= post.title
      %td
        - if post.cover_src.file
          %img{src: post.cover_src.url, width: '200px', height: '100px'}
        - else
          暂无封面
      %td= post.status_text
      %td
        = link_to "#{post.status_unpublished? ? '发布' : '取消发布'}", "javascript:void(0)", class: 'btn btn-xs btn-primary', onclick: "publish(this)", post_id: post.id
        = link_to '预览', post_path(post), class: 'btn btn-xs btn-primary', target: '_blank'
        = link_to '修改', edit_post_path(post), class: 'btn btn-xs btn-warning'
        = link_to '删除', post_path(post), method: :delete, class: 'btn btn-xs btn-danger', data: {confirm: '确认删除？'}
      %td
        = text_field_tag "order_num", post.order_num, style: "width: 50px"
        = link_to '更新排序', 'javascript:void(0)', class: 'btn btn-xs btn-primary', onclick: "update_order_num(this)", post_id: post.id


:javascript
  function publish(obj) {
    status = $(obj).text() == "发布" ? 1 : 0
    update($(obj).attr('post_id'), {status: status}, function() {
        console.log('success')
        $(obj).text(
          status == 1 ? '取消发布' : '发布'
        )
        $(obj).parent().prev().text(
          status == 1 ? '已发布' : '未发布'
        )
    })
  }
  
  function update_order_num(obj) {
    update($(obj).attr('post_id'), {order_num: $(obj).prev().val()}, function() { window.location.reload() })
  }

  function update(post_id, attributes, fn) {
    fn = fn || null
     $.ajax({
      url: '/posts/' + post_id,
      method: 'put',
      dataType: 'json',
      data: {post: attributes},
      success: function() {
        if (fn != null) {
          fn.call()
        }
      }
    })
  }